<template>
  <el-row :gutter="20">
    <el-col :span="12">
      <el-form ref="ruleFormRef" :model="baseInfo" :rules="rules" label-width="160px">
        <el-row>
          <el-col :span="24">
            <el-descriptions title="基本信息" />
          </el-col>
          <el-col :span="24">
            <el-form-item label="场地信息名称" prop="placeName">
              <el-input v-model="baseInfo.placeName" placeholder="请输入场地信息名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="场地地图" prop="baseMap">
              <el-upload
                :show-file-list="false"
                :action="uploadUrl"
                :http-request="httpRequest"
                :before-upload="handleChangeBaseMap"
                accept=".tif, .tiff"
              >
                <el-button type="primary" plain>上传 tif</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地块范围" prop="range" label-width="110px">
              <el-upload
                :show-file-list="false"
                :action="uploadUrl"
                :http-request="httpRequest"
                :on-change="handleRangeShp"
                accept=".shp"
              >
                <el-button type="primary" plain>上传 shp</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地下水等值线" prop="contourLine">
              <el-upload
                :show-file-list="false"
                :action="uploadUrl"
                :http-request="httpRequest"
                :on-change="handleChangeShp"
                accept=".shp"
              >
                <el-button type="primary" plain>上传 shp</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地下水调查点" prop="surveyPoints" label-width="110px">
              <el-upload
                :show-file-list="false"
                :action="uploadUrl"
                :http-request="httpRequest"
                :before-upload="handleChangePonits"
                accept=".xlsx, .xls"
              >
                <el-button type="primary" plain>上传 xlsx</el-button>
              </el-upload>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-descriptions title="水文地质信息" />
          </el-col>
          <el-col :span="12">
            <el-form-item label="包气带主要介质类型" prop="mediaType">
              <el-select v-model="baseInfo.mediaType">
                <template
                  v-for="dict in getIntDictOptions(DICT_TYPE.MEDIUM_TYPE)"
                  :key="dict.value"
                >
                  <el-option :value="dict.label" :label="dict.label" />
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包气带厚度" prop="thicknessAeration">
              <el-input v-model="baseInfo.thicknessAeration" placeholder="请输入包气带厚度">
                <template #append>m</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地下水渗透系数" prop="coefficient">
              <el-input v-model="baseInfo.coefficient" placeholder="请输入包气带厚度">
                <template #append>m/d</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含水层厚度" prop="thicknessWater">
              <el-input v-model="baseInfo.thicknessWater" placeholder="请输入含水层厚度">
                <template #append>m</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地下水位年际变化" prop="annualChanges">
              <el-input v-model="baseInfo.annualChanges" placeholder="请输入地下水位年际变化">
                <template #append>m</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="水力坡度" prop="slope">
              <el-input v-model="baseInfo.slope" placeholder="请输入水力坡度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地下水流速">
              <el-input
                :value="(Number(baseInfo.coefficient) * Number(baseInfo.slope)).toFixed(2) || ''"
              >
                <template #append>m/d</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含水层孔隙度" prop="porosity">
              <el-input v-model="baseInfo.porosity" placeholder="请输入含水层孔隙度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="pH" prop="ph">
              <el-input v-model="baseInfo.ph" placeholder="请输入pH" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Eh" prop="eh">
              <el-input v-model="baseInfo.eh" placeholder="请输入Eh">
                <template #append>mV</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="选择涉及污染物种类" prop="pollutantType">
              <el-checkbox-group v-model="baseInfo.pollutantType">
                <!-- <template v-for="item in target" :key="item.id">
                  <el-checkbox :label="item.target" :value="item.target" />
                </template> -->
                <template v-for="item in baseInfo.pollutantType" :key="item">
                  <el-checkbox :label="item" :value="item" />
                </template>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-col>
    <el-col :span="12">
      <div class="h-640px border-solid border-1 border-gray-300 border">
        <MyMap>
          <GeoTiff :data="imagLayer" />
          <geo :data="rangeLayer" :layer-style="featureStyle" :z-index="10" />
          <geo :data="linesLayer" :layer-style="lineStyle" :z-index="50" />
          <MapMarker :data="poniosLayer" :layer-style="pointsFun" :z-index="100" />
        </MyMap>
      </div>
    </el-col>
    <el-col :span="24" class="text-center mt-16px">
      <el-button type="primary" @click="next">下一步</el-button>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { FormInstance } from 'element-plus'
import { excelToJson } from '@/utils/xlsx'
import { useUpload } from '@/components/UploadFile/src/useUpload'
import MyMap from '../map/map.vue'
import MapMarker from '../map/marker'
import geo from '../map/geo'
import GeoTiff from '../map/geoTiff'
import type { BaseInfo, point } from '../types'
import type { List as Target } from '@/api/home/types'
import { shpFileTogGeojson } from '@/utils/shp'
import { lineStyle, featureStyle, pointsFun } from './style'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import type { FormRules } from 'element-plus'

const message = useMessage() // 消息
const { uploadUrl, httpRequest } = useUpload()

defineOptions({ name: 'Step1Form' })

// 污染物类型
const { target } = defineProps<{
  target: Target[]
}>()

const ruleFormRef = ref<FormInstance>()
const baseInfo = reactive<BaseInfo>({
  placeName: '',
  baseMap: '',
  surveyPoints: [],
  contourLine: '',
  range: '',
  pollutantType: [
    // '硝酸盐',
    // '耗氧量',
    // '氨氮',
    // '铅',
    // '苯',
    // '甲苯',
    // '氯苯',
    // '邻苯二甲酸',
    // '石油烃',
    // '氯苯',
    // '邻苯二甲酸',
    // '石油烃',
    // '挥发酚_以'
  ],
  mediaType: '',
  thicknessAeration: '',
  coefficient: '',
  thicknessWater: '',
  annualChanges: '',
  slope: '',
  porosity: '',
  ph: '',
  eh: ''
})

const rules: FormRules = {
  placeName: [{ required: true, message: '请输入', trigger: 'blur' }],
  // baseMap: [{ required: true, message: '请选择' }],
  range: [{ required: true, message: '请选择' }],
  // contourLine: [{ required: true, message: '请选择' }],
  surveyPoints: [{ required: true, message: '请选择' }],
  mediaType: [{ required: true, message: '请选择' }],
  pollutantType: [{ required: true, message: '请选择' }],
  thicknessAeration: [
    { required: true, message: '请输入' },
    { pattern: /^\d+(\.\d+)?$/, message: '格式不正确' }
  ],
  coefficient: [
    { required: true, message: '请输入' },
    { pattern: /^\d+(\.\d+)?$/, message: '格式不正确' }
  ],
  thicknessWater: [
    { required: true, message: '请输入' },
    { pattern: /^\d+(\.\d+)?$/, message: '格式不正确' }
  ],
  annualChanges: [{ required: true, message: '请输入' }],
  slope: [
    { required: true, message: '请输入' },
    { pattern: /^\d+(\.\d+)?$/, message: '格式不正确' }
  ],
  porosity: [
    { required: true, message: '请输入' },
    { pattern: /^\d+(\.\d+)?$/, message: '格式不正确' }
  ],
  ph: [
    { required: true, message: '请输入' },
    { pattern: /^\d+(\.\d+)?$/, message: '格式不正确' }
  ],
  eh: [
    { required: true, message: '请输入' },
    { pattern: /^\d+(\.\d+)?$/, message: '格式不正确' }
  ]
}

const next = async () => {
  await ruleFormRef.value?.validate()
  emits('next', {
    baseInfo: toRaw(baseInfo),
    imagLayer: imagLayer.value,
    rangeLayer: rangeLayer.value,
    poniosLayer: poniosLayer.value,
    linesLayer: linesLayer.value
  })
}

// 上传底图影像
const imagLayer = ref<any>()
const handleChangeBaseMap = async (file) => {
  const blob = new Blob([file], { type: 'image/tiff' })
  imagLayer.value = {
    sources: [{ blob: blob }]
  }
  return false
  // const reader = new FileReader()
  // reader.onload = function (e: any) {
  //   console.log(e.target.result)
  //   // 将读取的数据赋给img元素的src属性
  //   imagLayer.value = {
  //     sources: [{ url: e.target.result }]
  //   }
  // }
  // 读取文件内容
  // reader.readAsDataURL(file.raw)
  // if (file.status !== 'success') return
  // imagLayer.value = {
  //   sources: [
  //     {
  //       url: file.response.data
  //     }
  //   ]
  // }
  // baseInfo.baseMap = file.response.data
}

//  上传范围线shp
const rangeLayer = shallowRef()
const handleRangeShp = async (file) => {
  if (file.status !== 'success') return
  const data = await shpFileTogGeojson(file.raw)
  rangeLayer.value = data
  baseInfo.range = file.response.data
}

// 上传等值线shp
const linesLayer = shallowRef()
const handleChangeShp = async (file) => {
  if (file.status !== 'success') return
  const data = await shpFileTogGeojson(file.raw)
  linesLayer.value = data
  baseInfo.contourLine = file.response.data
}

// 上传点位excel
const poniosLayer = ref<any>()
const handleChangePonits = async (file) => {
  const data = (await excelToJson(file)) as point[]
  baseInfo.surveyPoints = data
  poniosLayer.value = generateGeojson(data)
  if (data.length > 0) {
    const keys = Object.keys(data[0])
    baseInfo.pollutantType = keys.filter((key: string) =>
      target.find((item) => item.target === key)
    )
  } else {
    baseInfo.pollutantType = []
    message.warning('点位数据不能为空')
  }
  return false
}

// 生成geojson
const generateGeojson = (data: point[]) => {
  return data.map((item: point) => {
    return {
      coordinate: [item.X, item.Y],
      ...item,
      text: item['点位']
    }
  })
}

const emits = defineEmits<{
  (e: 'next', data: any): void
}>()
</script>
